package com.lambkit.module.upms.apiroute;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import com.lambkit.common.util.StringUtils;
import com.lambkit.core.config.ConfigManager;
import com.lambkit.module.upms.UpmsConfig;
import com.lambkit.module.upms.UpmsManager;
import com.lambkit.module.upms.api.UpmsApiService;
import com.lambkit.module.upms.record.UpmsUser;
import com.lambkit.plugin.api.route.AbstractApiRequest;
import com.lambkit.plugin.api.route.AbstractApiRouteHandler;
import com.lambkit.plugin.api.route.ApiAction;
import com.lambkit.plugin.api.route.ApiException;

public class UpmsApiRouteHandler extends AbstractApiRouteHandler {

	public UpmsApiRouteHandler(String targetName) {
		super(targetName);
	}

	@Override
	protected AbstractApiRequest AccessSignCheck(AbstractApiRequest apiRequest, ApiAction apiAction,
			HttpServletRequest request, HttpServletResponse response) throws ApiException {
		String accessToken = apiRequest.getAccessToken();
		// 判断accessToken是否空
        if (StringUtils.isBlank(accessToken)) {
        	throw new ApiException(402, "验证失败：指定'token'不存在");
        }
		UpmsConfig upmsConfig = ConfigManager.me().get(UpmsConfig.class);
		String appid = StrKit.isBlank(upmsConfig.getAppId()) ? "lambkit-upms-server" : upmsConfig.getAppId();
		Map<String, String> params = new HashMap<String, String>();
    	params.put("appid", appid);
    	params.put("sessionid", accessToken);
    	if("server".equals(upmsConfig.getType())) {
    		UpmsUser user = UpmsManager.me().getUser(accessToken);
    		if(user!=null) {
    			apiRequest.setUserId(user.getUsername());
    			apiRequest.put("upmsUser", user);
    		} else {
    			throw new ApiException(402, "验证失败：签名失效");
    		}
    	} else {
    		//client
    		JSONObject result = JSONObject.parseObject(HttpKit.get(upmsConfig.getSsoServerUrl() + "/authenticate", params));
        	if(result == null || 0 == result.getIntValue("code")) {
        		throw new ApiException(402, "验证失败：签名失效");
        	} else {
        		String username = result.getString("message");
        		apiRequest.setUserId(username);
        		UpmsApiService upmsApiService = UpmsManager.me().getUpmsApiService();
        		if(upmsApiService!=null) {
        			UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername(username);
        			apiRequest.put("upmsUser", upmsUser);
        		}
        	}
    	}
		return apiRequest;
	}

	@Override
	protected AbstractApiRequest buildApiRequest(HttpServletRequest request) {
		// TODO Auto-generated method stub
		UpmsApiRequest apiRequest = new UpmsApiRequest();
		apiRequest.build(request);
		return apiRequest;
	}

}
